const Koa = require('koa')
const Router = require('koa-router');
const jwt = require('jsonwebtoken');
//用来签发令牌的
const jwtAuth = require('koa-jwt');
//用来检验的token 合不合法
const secret = 'it is a secret'
const app = new Koa()
const router = new Router();
router.get('/api/login', async ctx => {
    const { username, password } = ctx.query;
    console.log(username, password)
    if (username === 'kai' && password === '123') {
        const token = jwt.sign({
                data: { name: 'kai' },
                exp: Math.floor(Date.now() / 1000) + 60 * 60 //以秒为单位
            },
            secret
        );
        ctx.body = { code: 1, token }
    } else {
        ctx.status = 401;
        ctx.body = { code: 0, message: '用户名或者密码错误' }
    }
})
router.get('/api/userinfo', jwtAuth({ secret }), async ctx => {
    ctx.body = { code: 1, data: { name: 'jerry', age: 20 } }
})
router.get('/api/cart', async ctx => {
    ctx.body = { code: 1, data: { name: 'tom', age: 200 } }
})
app.use(router.routes())
app.listen(3003)